package middleware

import (
	"gin/common"
	"gin/model"
	"log"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//从header里获取token
		tokenString := c.GetHeader("access_token")
		if tokenString == "" || !strings.HasPrefix(tokenString, "licc ") {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "权限不足11",
			})
			c.Abort()
			return
		}
		tokenString = tokenString[5:]
		log.Println(tokenString)
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			c.JSON(401, gin.H{
				"code": 401,
				"msg":  "权限不足22",
			})
			log.Print(err)
			c.Abort()
			return
		}

		//验证通过后获取claims中的user_id
		Uid := claims.ID
		db := common.GetDb()
		var user model.User
		db.First(&user, Uid)
		//用户不存在
		if user.ID == 0 {
			c.JSON(401, gin.H{
				"code": 401,
				"msg":  "权限不足33",
			})
			c.Abort()
			return
		}
		//用户存在将user信息存入上下文
		c.Set("user", user)
		c.Next()
	}
}
